package com.zztl.infiniteBand.base


import com.zztl.infiniteBand.ui.view.mvpview.MvpView
import rx.Subscription
import java.lang.ref.WeakReference
import java.util.*

/**
 * @author bo.
 * @Date 2017/5/26.
 * @desc
 */

open class BasePresenter< V : MvpView> {

    private var viewWeak: WeakReference<V>? = null

    val view
        get() =viewWeak?.get()

    private var mSubscriptions: ArrayList<Subscription>? = null

    val isViewAttach: Boolean
        get() = viewWeak != null && viewWeak?.get() != null

    protected fun addSubscribe(subscriber: Subscription) {
        if (mSubscriptions == null) {
            mSubscriptions = ArrayList()
        }
        mSubscriptions?.add(subscriber)
    }


    fun attachView(view: V) {
        viewWeak = WeakReference(view)
    }

    fun detachView() {
        if (viewWeak != null) {
            viewWeak?.clear()
            viewWeak = null
        }
        if (null != mSubscriptions && mSubscriptions!!.size > 0) {
            for (i in mSubscriptions!!.indices) {
                mSubscriptions!![i].unsubscribe()
            }
            mSubscriptions = null
        }
    }

}
